package ext.tianma.bom.util;

import java.lang.reflect.InvocationTargetException;
import java.rmi.RemoteException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import wt.access.NotAuthorizedException;
import wt.change2.AffectedActivityData;
import wt.change2.ChangeActivity2;
import wt.change2.ChangeException2;
import wt.change2.ChangeHelper2;
import wt.change2.ChangeRecord2;
import wt.change2.Changeable2;
import wt.change2.VersionableChangeItem;
import wt.change2.WTChangeActivity2;
import wt.change2.WTChangeOrder2;
import wt.change2.WTChangeRequest2;
import wt.enterprise.Master;
import wt.enterprise.RevisionControlled;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.fc.ReferenceFactory;
import wt.fc.WTObject;
import wt.fc.WTReference;
import wt.fc.collections.WTArrayList;
import wt.inf.container.WTContainerException;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.method.RemoteMethodServer;
import wt.part.Quantity;
import wt.part.QuantityUnit;
import wt.part.WTPart;
import wt.part.WTPartMaster;
import wt.part.WTPartUsageLink;
import wt.pom.PersistenceException;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;
import wt.util.WTPropertyVetoException;
import wt.util.WTRuntimeException;
import wt.vc.VersionControlHelper;
import wt.vc.views.View;

import com.ptc.core.lwc.common.view.EnumerationDefinitionReadView;
import com.ptc.core.lwc.common.view.EnumerationEntryReadView;
import com.ptc.core.lwc.common.view.PropertyHolderHelper;
import com.ptc.core.lwc.server.TypeDefinitionServiceHelper;

import ext.tianma.bom.util.GenericUtil;

public class ChangeUtil {
	
	private static final Logger logger = LogR.getLogger(ChangeUtil.class.getName());
	
	public static void main(String[] args){
		
	}
	//得到受影响对象
		public static List<WTObject> getChangeablesBefore(WTChangeOrder2 ecn) throws Exception {
			List<WTObject> list = new ArrayList();
			QueryResult qr = ChangeHelper2.service.getChangeActivities(ecn);
			while (qr.hasMoreElements()) {
				WTChangeActivity2 eca = (WTChangeActivity2) qr.nextElement();
				QueryResult changeBefore = ChangeHelper2.service.getChangeablesBefore(eca);
				while (changeBefore.hasMoreElements()) {
					WTObject object = (WTObject) changeBefore.nextElement();
					list.add(object);
				}
			}
			return list;
		}
		
		//得到产生对象
		public static List<WTObject> getChangeablesBeforeMap(WTChangeOrder2 ecn) throws Exception {
			List<WTObject> list = new ArrayList();
			QueryResult qr = ChangeHelper2.service.getChangeActivities(ecn);
			while (qr.hasMoreElements()) {
				WTChangeActivity2 eca = (WTChangeActivity2) qr.nextElement();
				QueryResult changeAfter = ChangeHelper2.service.getChangeablesAfter(eca);
				while (changeAfter.hasMoreElements()) {
					WTObject object = (WTObject) changeAfter.nextElement();
					list.add(object);
				}
			}
			return list;
		}
    public static WTChangeOrder2 addChangeableBeforeToChangeNotice(WTChangeOrder2 cho, List list,
            WTChangeActivity2 eca) throws ChangeException2, WTException {
        try {
            if (!RemoteMethodServer.ServerFlag) {
                return (WTChangeOrder2) RemoteMethodServer.getDefault().invoke("addChangeableBeforeToChangeNotice",
                        ChangeUtil.class.getName(), null,
                        new Class[] { WTChangeOrder2.class, List.class, WTChangeActivity2.class },
                        new Object[] { cho, list, eca });
            } else {
                boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
                try {
                    if (eca != null) {
                        Vector<Changeable2> changeables = new Vector<Changeable2>();
                        for (Object obj : list) {
                            if (obj instanceof Changeable2) {
                                Changeable2 changeable = (Changeable2) obj;
                                changeables.add(changeable);
                            }
                        }
                        ChangeHelper2.service.storeAssociations(AffectedActivityData.class, eca, changeables);
                    }
                    cho = (WTChangeOrder2) PersistenceHelper.manager.refresh(cho);
                } finally {
                    SessionServerHelper.manager.setAccessEnforced(enforce);
                }
            }
        } catch (RemoteException e) {
            logger.error(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            logger.error(e.getMessage(), e);
        }
        return cho;
    }
    public static void removeResultObjectFromECA(final ChangeActivity2 changeTask, final Changeable2 changeable)
			throws WTException {
		ChangeRecord2 changeRecord = null;
		QueryResult result = PersistenceHelper.manager.find(
				ChangeRecord2.class, changeable,
				ChangeRecord2.CHANGEABLE2_ROLE, changeTask);
		while (result.hasMoreElements()) {
			changeRecord = (ChangeRecord2) result.nextElement();
			ChangeHelper2.service.deleteChangeRecord(changeRecord);
		}

	}
    
    public static void removeAffectedObjectFromECA(final ChangeActivity2 changeTask, final Changeable2 changeable)
			throws WTException {
		AffectedActivityData affectedActivityData = null;
		QueryResult result = PersistenceHelper.manager.find(
				AffectedActivityData.class, changeable,
				AffectedActivityData.CHANGEABLE2_ROLE, changeTask);
		while (result.hasMoreElements()) {
			affectedActivityData = (AffectedActivityData) result.nextElement();
			ChangeHelper2.service.deleteAffectedActivityData(affectedActivityData);
		}
	}
    public static WTChangeOrder2 addChangeableAfterToChangeNotice(WTChangeOrder2 cho, List list,
            WTChangeActivity2 eca) throws ChangeException2, WTException {
        try {
            if (!RemoteMethodServer.ServerFlag) {
                return (WTChangeOrder2) RemoteMethodServer.getDefault().invoke("addChangeableAfterToChangeNotice",
                        ChangeUtil.class.getName(), null,
                        new Class[] { WTChangeOrder2.class, List.class, WTChangeActivity2.class },
                        new Object[] { cho, list, eca });
            } else {
                boolean enforce = SessionServerHelper.manager.setAccessEnforced(false);
                try {
                    if (eca != null) {
                        Vector<Changeable2> changeables = new Vector<Changeable2>();
                        for (Object obj : list) {
                            if (obj instanceof Changeable2) {
                                Changeable2 changeable = (Changeable2) obj;
                                changeables.add(changeable);
                            }
                        }
                        ChangeHelper2.service.storeAssociations(ChangeRecord2.class, eca, changeables);
                    }
                    cho = (WTChangeOrder2) PersistenceHelper.manager.refresh(cho);
                } finally {
                    SessionServerHelper.manager.setAccessEnforced(enforce);
                }
            }
        } catch (RemoteException e) {
            logger.error(e.getMessage(), e);
        } catch (InvocationTargetException e) {
            logger.error(e.getMessage(), e);
        }
        return cho;
    }
}
